import type { Plugin } from 'vite'

const buildTimeKey = '__VITE_PLUGIN_BUILD_TIME__'
/** 插件和方法是否可运行 */
let isRun = false

/**
 * @param modes 除了production之外，还要在什么模式下运行此插件。比如`buildTimePlugin(['development'])`
 */
const buildTimePlugin = (modes: string[] = []): Plugin => {
  return {
    name: 'vite-plugin-build-time',
    config(_uc, { mode }) {
      isRun = mode === 'production' || modes.includes(mode)
    },
    transformIndexHtml() {
      if (!isRun) return
      return [
        {
          tag: 'script',
          children: `window.${buildTimeKey}=${Date.now()}`,
        },
      ]
    },
  }
}

export const getBuildTime = () => {
  if (!isRun) return 0
  if (typeof window === 'undefined') {
    console.warn('[vite-plugin-build-time] -> window未定义')
    return 0
  }
  const __window__ = window as typeof window & { [buildTimeKey]?: number }
  const buildTime = __window__[buildTimeKey] || 0
  if (!buildTime) console.warn('[vite-plugin-build-time] -> 无法获取打包时间，请查看文档')
  return buildTime
}

export default buildTimePlugin
